package com.design.observer.service.impl;

import com.design.observer.service.Observer;
import com.design.observer.service.Subject;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhengzihong
 * @version 1.0.0
 * @date 2018/9/8
 * @Description
 */
public class WeatherData implements Subject {

    private List<Observer> observers;

    private float temperature;

    private float humidity;

    private float pressure;


    public  WeatherData(){
        observers = new ArrayList<Observer>();
    }


    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        int i = observers.indexOf(o);
        if (i>=0){
            observers.remove(i);
        }
    }

    /**
     * 通知观察者
     */
    @Override
    public void notifyObservers() {
        for (int i = 0 ; i< observers.size(); i++){
            Observer observer = observers.get(i);
            observer.update(temperature,humidity,pressure);
        }
    }

    /**
     * 当从气象站得到更新观测值，我们通知观察者
     */
    public void measurementsChanged(){
        notifyObservers();
    }


    /**
     * 塞入最新数据
     * @param temperature
     * @param humidity
     * @param pressure
     */
    public void setMeasurements(float temperature, float humidity, float pressure){
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
}
